package com.wst.system.controller;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.wst.system.config.exception.GlobalExcetion;
import com.wst.system.config.job.*;
import com.wst.system.security.IsAdmin;
import com.wst.system.server.entity.SysJob;
import com.wst.system.server.entity.dto.SysJobDto;
import com.wst.system.server.entity.vo.OneDataVo;
import com.wst.system.server.entity.vo.PageSearchVo;
import com.wst.system.server.entity.vo.SysJobVo;
import com.wst.system.server.service.SysJobService;
import com.wst.system.util.EnumToListConverter;
import com.wst.system.util.ListUtils;
import com.wst.system.util.RandomNumber;
import com.wst.system.util.ResultUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/job")
public class SysJobController {

    @Autowired
    private SysJobService sysJobService;

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private QuarztUtils quarztUtils;

    @IsAdmin
    @PostMapping("/page")
    public JSONObject page(@RequestBody PageSearchVo vo){
        IPage<SysJob> page=sysJobService.pageSysJob(vo);
        if(page.getRecords().size()>0){
            List<SysJobDto> dtoList=new ArrayList<>();
            for(SysJob sysJob:page.getRecords()){
                SysJobDto dto=new SysJobDto();
                BeanUtils.copyProperties(sysJob,dto);
                dtoList.add(dto);
            }
            return ResultUtil.successInfoTable(page.getTotal(),dtoList);
        }
        return ResultUtil.successInfoTable(page.getTotal(),page.getRecords());
    }

    @IsAdmin
    @GetMapping("/gettimetypelist")
    public JSONObject getTimeTypeList(){
        List<Map<String,Object>> mapList=EnumToListConverter.convert(QuartzTimeEnum.values(),"type","typeName");
        return ResultUtil.successInfo(mapList);
    }

    @IsAdmin
    @GetMapping("/gettypelist")
    public JSONObject getTypeListController(){
        List<Map<String,Object>> mapList=EnumToListConverter.convert(QuartzEnum.values(),"type","status","quartClazz");
        return ResultUtil.successInfo(mapList);
    }

    @IsAdmin
    @PostMapping("/saveorupdatejob")
    public JSONObject saveOrUpdateJob(@RequestBody @Validated SysJobVo vo) throws GlobalExcetion {
        sysJobService.saveOrUpdateSysJob(vo);
        return ResultUtil.successInfo();
    }

    @IsAdmin
    @GetMapping("/getclass")
    public JSONObject getClassListController(@RequestParam("clazz")String clazz)  {
        if(!(clazz.startsWith("com.wst.system.config.job.model") || clazz.startsWith("com.wst.business.config.job.model"))){
            return ResultUtil.errorInfo(clazz+" 类必须在 com.wst.system.config.job 或 com.wst.business.config.job.model 路径下");
        }
        try {
            Class.forName(clazz);
            return ResultUtil.successInfo();
        }catch (ClassNotFoundException e){
        }
        return ResultUtil.errorInfo(clazz+"class 类未在当前系统发现");
    }

    @IsAdmin
    @GetMapping("/getclassmethodlist")
    public JSONObject getClassMethodListController(@RequestParam("clazz")String clazz)  {
        if(!(clazz.startsWith("com.wst.system.config.job.model") || clazz.startsWith("com.wst.business.config.job.model"))){
            return ResultUtil.errorInfo(clazz+" 类必须在 com.wst.system.config.job 或 com.wst.business.config.job.model 路径下");
        }
        try {
            Class<?> cls=Class.forName(clazz);
            Method[] method=cls.getDeclaredMethods();
            List<Map<String,String>> stringMapList=new ArrayList<>();
            for(Method m:method){
                Integer count=sysJobService.getCount(clazz,m.getName());
                if(count==0){
                    Map<String,String> map=new HashMap<>();
                    map.put("label",m.getName());
                    map.put("value",m.getName());
                    stringMapList.add(map);
                }
            }
            return ResultUtil.successInfo(stringMapList);
        }catch (ClassNotFoundException e){
        }
        return ResultUtil.errorInfo(clazz+"class 类未在当前系统发现");
    }

    @GetMapping("gettiggerorgroup")
    public JSONObject getTiggerOrGroupController(){
        Integer count=sysJobService.getCount();
        JSONObject jsonObject=new JSONObject();
        int num= RandomNumber.generateRandomNumber(3);
        jsonObject.put("group","Group_"+count+"_"+num);
        jsonObject.put("tigger","Tigger_"+count+"_"+num);
        return ResultUtil.successInfo(jsonObject);
    }

    @GetMapping("getannotationlist")
    public JSONObject getAnnotationListController(){
        Map<String, Object> beansWithAnnotation = applicationContext.getBeansWithAnnotation(Job.class);
        List<Map<String,String>> mapList=new ArrayList<>();
        // 遍历输出
        for (Map.Entry<String, Object> entry : beansWithAnnotation.entrySet()) {
            Map<String,String> map=new HashMap<>();
            Job job=entry.getValue().getClass().getAnnotation(Job.class);
            map.put("label",job.name());
            map.put("value",entry.getValue().getClass().getName());
            mapList.add(map);
        }
        return ResultUtil.successInfo(mapList);
    }

    @PostMapping("stop")
    public JSONObject stopSysJobController(@RequestBody @Validated OneDataVo vo) throws GlobalExcetion {
        SysJob sysJob=sysJobService.getById(vo.getId());
        if(sysJob==null){
            throw new GlobalExcetion(1,"任务不存在");
        }
        quarztUtils.stopQuarzt(sysJob);
        sysJobService.updateById(sysJob);
        return ResultUtil.successInfo();
    }

    @PostMapping("/start")
    public JSONObject startSysJonController(@RequestBody @Validated OneDataVo vo) throws GlobalExcetion {
        SysJob sysJob=sysJobService.getById(vo.getId());
        if(sysJob==null){
            throw new GlobalExcetion(1,"任务不存在");
        }
        quarztUtils.startQuarzt(sysJob);
        sysJobService.updateById(sysJob);
        return ResultUtil.successInfo();
    }

}
